package com.qf.openapi.web.master.interceptor;

import com.qf.openapi.web.master.entity.User;
import com.qf.openapi.web.master.service.UserService;
import com.qf.openapi.web.master.utils.Constants;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
public class AutoLoginInterceptor implements HandlerInterceptor {
    
    @Setter
    private UserService userService;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        
        
        
        //1.判断，如果session中有user对象了，那么直接重定向到/plateform.html
        HttpSession session = request.getSession();
    
        User sessionUser = (User) session.getAttribute(Constants.USER_SESSION_KEY);
        
        if (sessionUser != null){
            log.debug("用户已经登录过了，直接重定向到首页！");
            response.sendRedirect("/plateform.html");
            return false;
        }
        
        //2.检查请求中是否有userToken cookie，有的话还愿用户的登录状态
        Cookie[] cookies = request.getCookies();
        
        if (cookies != null && cookies.length > 0){
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if (name.equals(Constants.USER_TOKEN)){
                    String userTokenValue = cookie.getValue();
                    String[] usernameAndmd5Password = userTokenValue.split("-");
                    String username = usernameAndmd5Password[0];
                    String md5Password = usernameAndmd5Password[1];
                    
                    //返还用户登录状态
                    User user = userService.restoreUser(username, md5Password);
                    
                    //把user对象放入session域中
                    session.setAttribute(Constants.USER_SESSION_KEY, user);
                    
                    //重定向到plateform.html
                    log.debug("根据cookie还原用户登录状态成功，user={}", user);
                    response.sendRedirect("/plateform.html");
                    return false;
    
                }
            }
        }
        log.debug("没有免登录需要的cookie，进入登录页面");
        return true;
        
    }
}
